const { By, until } = require('selenium-webdriver')
const target = By.css('.ivu-table-tbody .ivu-table-row')


module.exports = function getAppList (driver, url) {
  return driver.then(() => {
    return driver.get(url)
  })
  .then(() => {
    return driver.wait(until.elementsLocated(target))
  })
  .then(() => {
    return driver.findElements(target)
  })
  .then((applist) => {
    const result = []
    const hrefTasks = []
    const textTasks = []
    const enableTasks = []
    applist.forEach((webEl) => {
      const p1 = webEl.findElement(By.css('.app-info .medium-txt a'))
      // const p2 = webEl.findElement(By.css('.ivu-table-column-center:last-child p'))
      hrefTasks.push(p1.getAttribute('href'))
      textTasks.push(p1.getText())
      // enableTasks.push(p2.getText())
    })
    const hrefPromise = Promise.all(hrefTasks)
    const textPromise = Promise.all(textTasks)
    // const enablePromise = Promise.all(enableTasks)
    return Promise.all([hrefPromise, textPromise])
  })
  .then(([hrefList, textList]) => {
    const result = []
    hrefList.forEach((href, index) => {
      const appid = href.match(/\/appid\/(\d+)/)[1]
      result.push({
        appid,
        appname: textList[index]
      })
    })
    return result
  })
}